import pygame
import sys
import os

# Add the current directory to Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from src.base_game import BaseGame
from src.resource_manager import ResourceManager
from games.pong import PongGame
from games.snake import SnakeGame


class GameLauncher:
    """Main game launcher and menu system"""
    
    def __init__(self, width: int = 800, height: int = 600):
        pygame.init()
        pygame.mixer.init()
        
        self.width = width
        self.height = height
        self.screen = pygame.display.set_mode((width, height))
        pygame.display.set_caption("Python Game Framework")
        
        self.clock = pygame.time.Clock()
        self.fps = 60
        self.running = True
        
        # Resource manager
        self.resource_manager = ResourceManager()
        
        # Games - manually register games
        self.games = {
            "Pong": PongGame,
            "Snake": SnakeGame
        }
        self.current_game = None
        
        # Menu
        self.in_menu = True
        self.selected_game = 0
        
        # Colors
        self.white = (255, 255, 255)
        self.black = (0, 0, 0)
        self.blue = (0, 0, 255)
        self.gray = (128, 128, 128)
        
        # Fonts
        self.title_font = pygame.font.Font(None, 72)
        self.menu_font = pygame.font.Font(None, 48)
        self.instruction_font = pygame.font.Font(None, 24)
        
        print(f"Loaded {len(self.games)} games: {list(self.games.keys())}")
        
    def handle_menu_events(self, event: pygame.event.Event) -> None:
        """Handle menu-specific events"""
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                self.selected_game = (self.selected_game - 1) % len(self.games)
            elif event.key == pygame.K_DOWN:
                self.selected_game = (self.selected_game + 1) % len(self.games)
            elif event.key == pygame.K_RETURN:
                if self.games:
                    game_class = list(self.games.values())[self.selected_game]
                    self.current_game = game_class(self.screen, self.resource_manager)
                    self.in_menu = False
                    
    def render_menu(self) -> None:
        """Render the main menu"""
        self.screen.fill(self.black)
        
        # Title
        title_text = self.title_font.render("Python Game Framework", True, self.white)
        title_rect = title_text.get_rect(center=(self.width // 2, 100))
        self.screen.blit(title_text, title_rect)
        
        # Game list
        if not self.games:
            no_games_text = self.menu_font.render("No games found", True, self.gray)
            text_rect = no_games_text.get_rect(center=(self.width // 2, 300))
            self.screen.blit(no_games_text, text_rect)
        else:
            start_y = 200
            for i, game_name in enumerate(self.games.keys()):
                color = self.blue if i == self.selected_game else self.white
                game_text = self.menu_font.render(game_name, True, color)
                text_rect = game_text.get_rect(center=(self.width // 2, start_y + i * 60))
                self.screen.blit(game_text, text_rect)
                
                # Selection indicator
                if i == self.selected_game:
                    pygame.draw.rect(self.screen, self.blue, 
                                   (text_rect.left - 10, text_rect.top - 5, 
                                    text_rect.width + 20, text_rect.height + 10), 2)
        
        # Instructions
        if self.games:
            instructions = [
                "Use UP/DOWN arrows to navigate",
                "Press ENTER to select a game",
                "Press ESC to quit"
            ]
        else:
            instructions = [
                "Add game files to the 'games' directory",
                "Press ESC to quit"
            ]
            
        for i, instruction in enumerate(instructions):
            instruction_text = self.instruction_font.render(instruction, True, self.gray)
            text_rect = instruction_text.get_rect(center=(self.width // 2, 
                                                         self.height - 100 + i * 25))
            self.screen.blit(instruction_text, text_rect)
            
    def run(self) -> None:
        """Main application loop"""
        while self.running:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        if self.in_menu:
                            self.running = False
                        else:
                            self.in_menu = True
                            self.current_game = None
                    elif self.in_menu:
                        self.handle_menu_events(event)
                elif not self.in_menu and self.current_game:
                    self.current_game.handle_event(event)
                    
            if self.in_menu:
                self.render_menu()
            else:
                if self.current_game:
                    dt = self.clock.tick(self.fps) / 1000.0
                    self.current_game.update(dt)
                    self.current_game.render()
                    
                    # Check if game is still running
                    if not self.current_game.running:
                        self.in_menu = True
                        self.current_game = None
                        
            pygame.display.flip()
            
        pygame.quit()
        sys.exit()


if __name__ == "__main__":
    launcher = GameLauncher()
    launcher.run()